<?php
class LForm extends CFormModel
{
    public $username;
    public $password;
    public $rememberMe=false;
    public $verifyCode;
    private $_identity;

    public function rules()
    {
        return array(
            array('verifyCode', 'captcha', 'allowEmpty'=>!UserModule::doCaptcha('registration')),
            array('username, password', 'required'),
            array('password', 'authenticate'),
        );
    }

    public function authenticate($attribute,$params)
    {
        if(!$this->hasErrors())  // 我们只想校验没有输入错误
        {
            $identity=new UserIdentity($this->username,$this->password);
            if($identity->authenticate())
            {
                $duration=$this->rememberMe ? 3600*24*30 : 3600; // 30 天
                $this->login($identity,$duration);
            }
            else
                $this->addError('password','Incorrect password.');
        }
    }

    public function login()
    {
        if($this->_identity===null)
        {
            $this->_identity=new UserIdentity($this->username,$this->password);
            $this->_identity->authenticate();
        }
        if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
        {
            $duration=$this->rememberMe ? 3600*24*30 : 3600; // 30 days
            Yii::app()->user->login($this->_identity,$duration);
            return true;
        }
        else
            return false;
    }
}